package com.bff.gaia.client.cli;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import com.bff.gaia.api.common.Plan;
import com.bff.gaia.configuration.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

public class NettyServers {
	public String[] str;
	public  static List<String> strs=new ArrayList<>();
	public Configuration config;
	public static PriorityQueue<Plan> q = new PriorityQueue<Plan>();
	private final List<CustomCommandLine<?>> customCommandLines;
	public static int count_clinets=0;
	public static int connect_num=10; //设置一个最大；链接数，超过这个连接数的链接无效。合并只是根据这个链接数的connect合并
	public NettyServers(Configuration configs,List<CustomCommandLine<?>> customCommandLines)
	{
		this.customCommandLines=customCommandLines;
		this.config=configs;
	}
	public void bind(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					System.out.println("有客户端连接上来:"+ch.localAddress().toString());
					ch.pipeline().addLast(new ObjectEncoder());
					ch.pipeline().addLast(new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingConcurrentResolver(null))); // 最大长度
					ch.pipeline().addLast(new ServerHandlers(config,customCommandLines));
				}
			});
			ChannelFuture f = b.bind(port).sync();
			System.out.println("等待连接：");
			f.channel().closeFuture().sync();

		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}


}